let socket = null,
  did = getUrlParam("did"),
  vid = getUrlParam("vid"),
  token = localStorage.getItem("token"),
  runStatus = ["通讯异常", "手动", "自动", "警告", "故障"];
window.onload = function () {
  if (token) {
    if (vid) {
      getVideoDetail(vid, token);
    }
    if (did) {
      getDeviceDetail(did, token);
    }
  }
};

function getDeviceDetail(id) {
  fetch(`/iot_device/device/getDeviceDetail?id=${id}`, {
    headers: {
      "Content-type": "application:/x-www-form-urlencoded:charset=UTF-8",
      token: token,
    },
  }).then(async (response) => {
    let res = await response.json();
    if (res.message == 200) {
      console.info(res.data);
      getHistoryData(+id, res.data.modelId);
      createWebsocket(did, res.data.modelId);
    }
  });
}

function getHistoryData(deviceId, modelId) {
  let keys = [];
  if (location.pathname.includes("deviceVideo-HPPlate")) {
    keys = [
      "frontTemp",
      "K58",
      "K60",
      "K61",
      "K62",
      "K53",
      "K54",
      "K55",
      "K56",
      "K57",
      "backTemp",
      "K59",
      "Condition",
      "Yield",
      "K0",
      "K1",
    ];
  } else if (location.pathname.includes("deviceVideo-packer")) {
    keys = [
      "K8",
      "K9",
      "K10",
      "K11",
      "K29",
      "K30",
      "K2",
      "K3",
      "K4",
      "K5",
      "K6",
      "K7",
      "K31",
      "K32",
      "frontTemp",
      "backTemp",
      "K53",
      "K54",
      "Condition",
      "Yield",
      "K0",
      "K1",
    ];
  }
  let params = [];
  keys.forEach((key) => {
    params.push({ deviceId, modelId, vk: key });
  });
  params = JSON.stringify(params);
  fetch(encodeURI(`/iot_device/device/getScadaVariable?data=${params}`), {
    headers: {
      "Content-type": "application:/x-www-form-urlencoded:charset=UTF-8",
      token: token,
    },
  }).then(async (response) => {
    let res = await response.json();
    if (res.message == 200) {
      res.data.forEach((item) => {
        if (item.vk === "Condition") {
          document.querySelector(`.${item.vk}`).textContent = runStatus[item.value];
        } else {
          document.querySelector(`.${item.vk}`).textContent = item.value ?? "-";
        }
      });
    }
  });
}

function getVideoDetail(id) {
  fetch(`/iot_device/device/getVideoSource?id=${id}`, {
    headers: {
      "Content-type": "application:/x-www-form-urlencoded:charset=UTF-8",
      token: token,
    },
  }).then(async (response) => {
    let res = await response.json();
    if (res.message == 200) {
      console.info(res.data);
      let accessToken = getUrlParam(
        "accessToken",
        res.data.Source.split("?")[1]
      );
      let url = getUrlParam("url", res.data.Source.split("?")[1]);
      let player = new EZUIKit.EZUIKitPlayer({
        id: "video", // 视频容器ID
        controls: false,
        accessToken,
        url,
      });
    }
  });
}

function createWebsocket(did, mid) {
  let host = location.host.includes("localhost")
    ? "s2.v3.hignton.com:9080"
    : location.host;
  let h = location.host.includes("devicecloud.chaint.net") ? "wss://" : "ws://";
  let url = `${h}${host}/base/iot_websocket/ws/`;
  socket = new WebSocket(url, [token]);
  socket.onopen = (res) => {
    let param = {
      device_id: +did,
      product_id: +mid,
      type: 2,
      is_single: true, //是否单独监听此设备， 若为true 则客户端只会监听此设备
    };
    socket.send(JSON.stringify(param));
  };
  socket.onmessage = (res) => {
    let data;
    if (res.data) {
      localStorage.setItem(`${did}TimeData`, res.data);
      data = JSON.parse(res.data);
    } else {
      let resData = localStorage.getItem(`${did}TimeData`);
      if (resData) data = JSON.parse(resData);
      else data = {};
    }
    let points = data.Record ? data.Record.Points : [];
    points.forEach((item) => {
      let el = document.querySelector("." + item.K);
      if (el) {
        if (item.K === "Condition") {
          el.textContent = runStatus[item.V];
        } else {
          el.textContent = item.V;
        }
      }
    });
  };
  socket.addEventListener("error", (event) => {
    console.log("连接发生错误，尝试重新连接");
    setTimeout(() => {
      createWebsocket(did, mid);
    }, 3000);
  });
}

// 获取URL地址参数
function getUrlParam(name, url = window.location.search.substr(1)) {
  let vars = url.split("&");
  for (let i = 0; i < vars.length; i++) {
    let pair = vars[i].split("=");
    if (pair[0] == name) {
      return pair[1];
    }
  }
  return false;
}
